package 反转字符串中的单词;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 反转字符串中的单词
 * @date 2022/10/22 16:19
 */
public class Demo151 {
    public static void main(String[] args) {
        String the_sky_is_blue = reverseWords("  hello world  ");
        System.out.println(the_sky_is_blue);

    }
    public  static String reverseWords(String s) {
        //去除多余的空格
       String str=deleteSpace(s);
       //翻转整个字符串
       str=reverse(str,0,str.length()-1);
       int index=0;
        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i)==' '){
                str=reverse(str,index,i-1);
                index=i+1;
            }
        }
        return reverse(str, index, str.length() - 1);
    }

    private static String reverse(String str, int left, int right) {
        char[] chars = str.toCharArray();
        while (left<right){
            char temp=chars[left];
            chars[left++]=chars[right];
            chars[right--]=temp;
        }
        return new String(chars);
    }

    private static  String deleteSpace(String s) {
         int start=0;
         int end=s.length()-1;
         //去除前面空格
         while (s.charAt(start)==' '){
             start++;
         }
         //去除后面空格
        while (s.charAt(end)==' '){
            end--;
        }
        s=s.substring(start,end+1);
        //去除中间空格,这里用到了快慢指针，移除元素
        char[] chars = s.toCharArray();
        StringBuilder res=new StringBuilder();
        for (int i = 0; i < chars.length-1; i++) {
            if(chars[i]!=' '){
                res.append(chars[i]);
            }else if(chars[i+1]!=' '){
                res.append(chars[i]);
            }
        }
        res.append(chars[chars.length-1]);
        return res.toString();
    }
}
